package org.cuckoocs.xyfile.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.cuckoocs.xyfile.tool.Tool;

public class XYFileIndex extends ByteFile {
	
	static {
		size = (new XYFileIndex().toByte()).length;
	}
	
	public static final int size;
	
	private int key;
	private int pass;
	private long offset;
	private int length;

	private XYFileIndex(){}
	
	public XYFileIndex(byte[] bytes) {
		repair(bytes);
	}

	public XYFileIndex(int key, int pass, long offset, int length) {
		super();
		this.key = key;
		this.pass = pass;
		this.offset = offset;
		this.length = length;
	}

	public int getKey() {
		return key;
	}

	public void setKey(int key) {
		this.key = key;
	}

	public int getPass() {
		return pass;
	}

	public void setPass(int pass) {
		this.pass = pass;
	}

	public long getOffset() {
		return offset;
	}

	public void setOffset(long offset) {
		this.offset = offset;
	}

	public int getLenth() {
		return length;
	}

	public void setLenth(int lenth) {
		this.length = lenth;
	}

	public long unique(){
		return Tool.unique(key, pass);
	}
	
	@Override
	public byte[] toByte() {
		byte[] buff = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		try (DataOutputStream dos = new DataOutputStream(baos)) {
			dos.writeInt(this.key);
			dos.writeInt(this.pass);
			dos.writeLong(this.offset);
			dos.writeInt(this.length);

			buff = baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buff;
	}

	@Override
	public void repair(byte[] bytes) {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

		try (DataInputStream dis = new DataInputStream(bais)) {
			this.key = dis.readInt();
			this.pass = dis.readInt();
			this.offset = dis.readLong();
			this.length = dis.readInt();

			dis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
